package com.alibaba.csp.sentinel.dashboard.util;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
* rule序列化工具
* @author cjunxian
* @date 2021/6/25
*/
@Component
public class ConverterUtils {

    /**
     * 将naocs上的规则转为对应的ruleEntity
     * @param configService
     * @param appName
     * @param postfix data-id前缀
     * @param groupId nacos中的组名
     * @param timeout 超时时间
     * @param ruleType 规则类型
     * @param <T>
     * @return
     * @throws NacosException
     */
    public <T> List<T> pullRule(ConfigService configService, String appName, String postfix, String groupId, int timeout, Class<T> ruleType) throws NacosException {
        String rules = configService.getConfig(appName + postfix,
                groupId, timeout);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return JSONObject.parseArray(rules,ruleType);
    }


    public <T> void pushRule(ConfigService configService, String appName, String postfix, String groupId, List<T> rules,Class<T> ruleType) throws NacosException {

        configService.publishConfig(appName + postfix,
                groupId, JSONObject.toJSONString(rules));

    }

}
